<template>
  <template v-if="loaded">
    <ProForm
      ref="formRef"
      :model="formState"
      :items="items"
      :disabled="readonly"
      :onValuesChange="onValuesChange"
      :formColLayout="formColLayout()"
      :requiredMark="!readonly"
      class="pro-form-modal"
      v-bind="formProps"
    >
    </ProForm>
    <FooterButtons
      :formState="formState"
      :formRef="formRef"
      v-model:readonly="readonly"
      :serviceApi="postIntensityMeter"
      @refresh="refresh"
      :fastConfig="fastConfig"
    />
  </template>
</template>

<script setup lang="tsx">
import { computed, nextTick, ref, shallowRef } from 'vue';
import { Input, InputPassword } from 'ant-design-vue';
import { ProForm, ProFormProps } from '@/components/ProForm';
import { ItemProps } from '@/components/ProForm/interface';
import { getIntensityMeterConfig, postIntensityMeter } from '@/api/device';
import FooterButtons from './FooterButtons.vue';

defineOptions({
  name: 'Meter',
});

interface Props {
  pageData: any;
  readonly?: any;
  fastConfig?: boolean;
}
const props = defineProps<Props>();
const loaded = ref(false);
const readonly = ref(props.readonly ?? true);
const formRef = shallowRef();
const formState = ref<Record<string, any>>({});
const column = 3;
const formColLayout = () => {
  const num = 24 / column;
  return { xs: num, sm: num, md: num, lg: num };
};
const formProps = computed<ProFormProps>(() => {
  return {
    labelCol: { span: 6 },
    wrapperCol: { span: 20 },
  };
});
const onValuesChange = (
  values: Record<string, any>,
  state: Record<string, any>,
) => {
  formState.value = {
    ...formState.value,
    ...state,
  };
};
const refresh = () => {
  loaded.value = false;
  nextTick(() => {
    loaded.value = true;
  });
};
const itemObj = (
  label: string,
  type: any,
  field: string,
  required: boolean = false,
  props?: any,
  layout?: any,
  rules: any = [],
): ItemProps => {
  return {
    label,
    type,
    field,
    props: {
      placeholder: `请${type == 'input' ? '输入' : '选择'}${label}`,
      allowClear: false,
      ...props,
    },
    rules: [
      {
        required,
        message: `请${type == 'input' ? '输入' : '选择'}${label}`,
        trigger: 'blur',
      },
      ...rules,
    ],
    ...layout,
  };
};
const itemRender = (title: string): ItemProps => {
  return {
    label: { title },
    type: 'input',
    field: 'h5',
    formItemRender() {
      return <h5 class='h5'>{title}</h5>;
    },
  };
};
const radioOptions = [
  { value: 0, label: '关闭' },
  { value: 1, label: '开启' },
];

const items = computed<ProFormProps['items']>(() => [
  itemRender('基础参数'),
  itemObj('烈度计类型', 'select', 'intensityType', true, {
    options: [
      { value: 0, label: '内置烈度计' },
      { value: 1, label: '外置烈度计' },
    ],
    onChange: () => {
      formRef.value.setFiledValue('samplingRate', undefined);
    },
  }),
  itemObj('台网名称', 'input', 'netName', true),
  itemObj('台站名称', 'input', 'siteName', true),
  itemObj('位置标识', 'input', 'positionLabel'),
  ...(formState.value.channelLabel
    ? [itemObj('通道标识', 'input', 'channelLabel', false, { disabled: true })]
    : []),
  itemObj('采样率', 'select', 'samplingRate', false, {
    options: [
      { value: '50', label: '50' },
      { value: '100', label: '100' },
      ...(formState.value.intensityType == 0
        ? [{ value: '200', label: '200' }]
        : []),
    ],
  }),
  itemObj('相位', 'select', 'filerType', false, {
    options: [
      { value: 0, label: '线性相位' },
      { value: 1, label: '最小相位' },
    ],
  }),
  ...(formState.value.factor
    ? [
        itemObj('烈度计格值', 'input', 'factor', false, undefined, {
          customRender(formState: any) {
            return (
              <Input
                value={formState.factor / 10000}
                suffix='Gal/mv'
                disabled
              />
            );
          },
        }),
      ]
    : []),

  itemObj('烈度计高程', 'input', 'high'),
  itemObj('安装角度', 'input', 'installationAngle'),
  itemObj('位置', 'select', 'installationMethod', false, {
    options: [
      { value: 0, label: '水平' },
      { value: 1, label: '壁挂' },
    ],
  }),
  itemRender('存储参数'),
  itemObj('本地存储', 'radio', 'isOpenLocalSave', false, {
    options: radioOptions,
  }),
  itemObj(
    '本地存储工作模式',
    'radio',
    'localWorkMode',
    false,
    {
      options: [
        { value: 0, label: '触发波形模式' },
        { value: 1, label: '连续+触发波形模式' },
      ],
    },
    { colProps: { span: 10 }, labelCol: { span: 7 } },
  ),
  itemObj('线上存储', 'radio', 'isOpenOnlineSave', false, {
    options: radioOptions,
  }),
  itemObj(
    '线上存储工作模式',
    'radio',
    'onlineWorkMode',
    false,
    {
      options: [
        { value: 0, label: '触发波形模式' },
        { value: 1, label: '连续波形模式' },
      ],
    },
    { colProps: { span: 10 }, labelCol: { span: 7 } },
  ),
  itemObj('服务地址', 'input', 'host'),
  itemObj('服务端口', 'input', 'port'),
  itemObj('密码', 'input', 'password', false, undefined, {
    customRender(formState: any) {
      return (
        <InputPassword
          v-model:value={formState.password}
          placeholder='请输入文件服务私密密钥'
          autocomplete='no-password'
        />
      );
    },
  }),
]);

props.pageData.intensityMeterConfigMessagesJson
  ? (() => {
      formState.value = JSON.parse(
        props.pageData.intensityMeterConfigMessagesJson,
      );
      loaded.value = true;
    })()
  : getIntensityMeterConfig(props.pageData.code).then((res: any) => {
      formState.value = res.data;
      formState.value.code = props.pageData.code;
      loaded.value = true;
    });

defineExpose({
  async save() {
    const data = await formRef.value.validate();
    props.pageData.intensityMeterConfigMessagesJson = JSON.stringify(data);
  },
});
</script>
